<template>
  <el-drawer
    :title="copName"
    size="60%"
    :visible.sync="isShowDrawer"
    @close="closeDrawer"
  >
    <div>
      <el-form
        ref="form"
        class="doumee-form"
        :model="param"
        label-width="140px"
        label-suffix="："
        :rules="rules"
      >
        <div class="property-title">优惠券属性</div>
        <el-form-item label="优惠券名称" prop="couponsName">
          <el-input
            v-model="param.couponsName"
            class="w400"
            placeholder="请输入优惠券名称"
            maxlength="30"
          />
        </el-form-item>
        <el-form-item label="类型" class="select-style" prop="couponsType">
          <el-select v-model="param.couponsType" :disabled="id != ''" class="w200" @change="changeType">
            <el-option label="折扣券" value="0" />
            <el-option label="代金券" value="1" />
          </el-select>
        </el-form-item>
        <div v-if="param.couponsType == '0'" class="df">
          <el-form-item
            key="1"
            label="优惠规则"
            prop="miniNum"
            :rules="{
              required: true, message: '请输入', trigger: 'change'
            }"
          >
            <span class="mr10">订单实付满</span>
            <el-input-number v-model="param.miniNum" :min="0" :step="1" class="w100 mr10" />
            <span class="mr10">元 享折扣</span>
          </el-form-item>
          <el-form-item
            label-width="0"
            prop="discountNum"
            :rules="{
              required: true, message: '请输入', trigger: 'change'
            }"
          >
            <el-input-number v-model="param.discountNum" :precision="1" :min="0.1" :max="10" class="w100 mr10" />
            <span class="mr20">折</span>
            <span class="placeholder9">0<折扣<10，支持1位小数</span>
          </el-form-item>
        </div>
        <div v-if="param.couponsType == '1'" class="df">
          <el-form-item
            key="2"
            label="优惠规则"
            prop="miniNum"
            :rules="{
              required: true, message: '请输入', trigger: 'change'
            }"
          >
            <span class="mr10">订单实付满</span>
            <el-input-number v-model="param.miniNum" :min="0" :step="1" class="w100 mr10" />
            <!-- <el-input
              v-model="param.useRules.miniNum"
              onkeyup="value=value.replace(/[^\d^\.]/g,'')"
              onkeypress="return event.keyCode>=48&&event.keyCode<=57"
              class="w100 mr10"
            /> -->
            <span class="mr10">元 减</span>
          </el-form-item>
          <el-form-item prop="discountNum" label-width="0">
            <el-input-number v-model="param.discountNum" :min="0" :step="1" class="w100 mr10" />
            <!-- <el-input
              v-model="param.discountNum"
              onkeyup="value=value.replace(/[^\d^\.]/g,'')"
              onkeypress="return event.keyCode>=48&&event.keyCode<=57"
              class="w100 mr10"
            /> -->
            <span class="mr20">元</span>
          </el-form-item>
        </div>
        <el-form-item label="使用说明">
          <el-input
            v-model="param.useDes"
            style="width: 560px"
            type="textarea"
            :autosize="{ minRows: 3}"
            placeholder="请输入内容"
          />
          <div class="placeholder9">使用说明仅可描述优惠券的使用规则，例如本优惠券不可转让等</div>
        </el-form-item>
        <div class="mb20">
          <span class="property-title">时间设置</span>
          <span class="sub-title">限领时间，优惠券可用时间设置</span>
        </div>
        <div style="display: flex;align-items: center;">
          <el-form-item label="限领日期" prop="timeLimit">
            <el-date-picker
              v-model="param.timeLimit"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="yyyy-MM-dd HH:mm:ss"
              value-format="yyyy-MM-dd HH:mm:ss"
              :picker-options="pickerOptionsS"
            />
          </el-form-item>
        </div>
        <div class="df">
          <el-form-item label="可用时间" class="select-style" prop="validityType">
            <el-select
              v-model="param.validityType"
              class="w200 mr20"
              placeholder="请选择可用时间"
            >
              <el-option label="固定日期" value="0" />
              <el-option label="购买后生效" value="1" />
            </el-select>
          </el-form-item>
          <el-form-item v-if="param.validityType === '0'" label-width="0" prop="validityTime">
            <span>固定时间：</span>
            <el-date-picker
              v-model="param.validityTime"
              type="daterange"
              class="w400"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd"
              :picker-options="pickerOptions"
            />
          </el-form-item>
          <el-form-item v-if="param.validityType === '1'" label-width="0" prop="validityDays">
            <span>有效期：</span>
            <el-input
              v-model="param.validityDays"
              class="w200 mr10"
              onkeyup="value=value.replace(/[^\d^]/g,'')"
              oninput="if(value<=0) { value = ''}"
              placeholder="请输入日期"
            />
            <span>天</span>
          </el-form-item>
        </div>
        <el-form-item label="时间段限制" prop="timer">
          <el-radio v-model="param.rulesTimeSectionFlag" label="1" @change="changeTimes">全时段可用</el-radio>
          <el-radio v-model="param.rulesTimeSectionFlag" label="0" @change="changeTimes">指定时段可用</el-radio>
          <div v-if="param.rulesTimeSectionFlag == '0'">
            <el-checkbox-group v-model="selWeekList" class="mb10">
              <el-checkbox v-for="item in weekList" :key="item.value" :label="item.value">{{ item.label }}</el-checkbox>
            </el-checkbox-group>
            <div class="df">
              <span class="mr10">每日</span>
              <div>
                <el-time-picker
                  v-model="param.useTime"
                  is-range
                  class="w200 mr10"
                  format="HH:mm"
                  value-format="HH:mm"
                  range-separator="~"
                  start-placeholder="开始时间"
                  end-placeholder="结束时间"
                  placeholder="选择时间范围"
                />
              </div>
              <span>可用</span>
            </div>
          </div>
        </el-form-item>
        <div class="mb20">
          <span class="property-title">发放规则</span>
          <span class="sub-title">发行数量、渠道及限领数量等</span>
        </div>
        <el-form-item label="发行数量" prop="circulation">
          <el-input
            v-model="param.circulation"
            class="w400"
            onkeyup="value=value.replace(/[^\d^\.]/g,'')"
            onkeypress="return event.keyCode>=48&&event.keyCode<=57"
            oninput="if(value<0) { value = ''}"
            placeholder="请输入发行数量"
          />
        </el-form-item>
        <el-form-item label="发放渠道" prop="couponsChannel">
          <el-select
            v-model="param.couponsChannel"
            class="w200"
            placeholder="请选择发放渠道"
            prop="couponsChannel"
            :disabled="$route.query.id?true:false"
          >
            <el-option label="用户领取" value="1" />
            <el-option label="积分兑换" value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="每人限领数量">
          <el-radio v-model="param.limitGetFlag" label="1" @change="changeLimit">不限制</el-radio>
          <el-radio v-model="param.limitGetFlag" label="0" @change="changeLimit">限制</el-radio>
          <template v-if="param.limitGetFlag == '0'">
            <el-select
              v-model="param.restrictType"
              class="w100 mr10"
            >
              <template v-for="item in limitNum">
                <el-option :key="item.value" :label="item.label" :value="item.value" />
              </template>
            </el-select>
            <el-input
              v-model="param.peoLimit"
              class="w100 mr10"
              oninput="value=value.replace(/^(0+)|[^\d]+/g,'')"
            />
            <span>张</span>
          </template>
        </el-form-item>
        <div class="mb20">
          <span class="property-title">适用规则</span>
          <span class="sub-title">适用的场馆、项目、订单、支付方式等</span>
        </div>
        <el-form-item label="支付方式">
          <el-radio v-model="param.rulesPayMethodFlag" label="1" @change="changePayMethods">全部支付方式可用</el-radio>
          <el-radio v-model="param.rulesPayMethodFlag" label="0" @change="changePayMethods">指定支付方式可用</el-radio>
          <el-checkbox-group v-if="param.rulesPayMethodFlag == '0'" v-model="selPayTypeList">
            <el-checkbox
              v-for="(item, index) in payTypeList"
              :key="index"
              :label="item.value"
            >{{ item.name }}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="订单类型">
          <el-radio v-model="param.rulesOrderTypeFlag" label="1" @change="changeOrderType">全部订单可用</el-radio>
          <el-radio v-model="param.rulesOrderTypeFlag" label="0" @change="changeOrderType">指定订单可用</el-radio>
          <el-checkbox-group v-if="param.rulesOrderTypeFlag == '0'" v-model="selOrderTypeList">
            <el-checkbox
              v-for="(item, index) in orderTypeList"
              :key="index"
              :label="item.id"
            >{{ item.name }}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item class="margin-t-20" label="适用场馆">
          <el-radio v-model="param.rulesVenueFlag" label="1" @change="changeVenue">全部场馆可用</el-radio>
          <el-radio v-model="param.rulesVenueFlag" label="0" @change="changeVenue">指定场馆可用</el-radio>
          <div v-if="param.rulesVenueFlag == '0'" class="venue-project">
            <div class="venue-list">
              <el-checkbox-group v-model="checkedVenue" @change="checkVenue">
                <el-checkbox
                  v-for="(item, index) in venueProjectListData"
                  :key="index"
                  :label="item.id"
                >{{ item.name }}</el-checkbox>
              </el-checkbox-group>
            </div>
          </div>
        </el-form-item>
        <el-form-item v-if="param.rulesVenueFlag === '0'" label="适用项目">
          <el-radio v-model="param.rulesProjectFlag" label="1" @change="changeItems">全部项目可用</el-radio>
          <el-radio v-model="param.rulesProjectFlag" label="0" @change="changeItems">指定项目可用</el-radio>
          <el-table v-if="param.rulesProjectFlag == '0'" :data="venueProjectListDataForTable" border>
            <el-table-column prop="name" label="场馆" width="200px" />
            <el-table-column label="项目">
              <template slot-scope="scope">
                <el-checkbox-group v-model="checkedItems">
                  <el-checkbox
                    v-for="(item, index) in scope.row.projects"
                    :key="index"
                    :label="item.id"
                    @change="checkProject()"
                  >{{ item.projectName }}</el-checkbox>
                </el-checkbox-group>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
        <div class="separate" />
        <div>
          <el-button v-preventReClick type="primary" :loading="submitLoading" @click="formOnSubmit('form')">确认</el-button>
          <el-button @click="closeDrawer">取消</el-button>
        </div>
      </el-form>
    </div>
  </el-drawer>
</template>

<script>
import {
  couponsAdd,
  venueList,
  orderTypeList,
  venueProjectList,
  allConfigList,
  couponsEdit,
  couponsDetail
} from '@/api'
import { weekList, limitNum, rules } from './config'
import { pickerOptionsS, pickerOptions } from '@/utils/config'
export default {
  name: 'CouponAdd',
  data() {
    return {
      id: '',
      isShowDrawer: false,
      submitLoading: false,
      weekList,
      limitNum,
      pickerOptions,
      pickerOptionsS,
      copName: '新增优惠券',

      payTypeList: [], // option支付方式
      orderTypeList: [],
      venueProjectListData: [],

      filters: {},
      selWeekList: [], // param 选中时间
      selPayTypeList: [], // param 选中支付方式
      selOrderTypeList: [], // param 选中订单类型
      checkedVenue: [], // param 选中场馆
      checkedItems: [], // param
      venueProjectListDataForTable: [],

      param: {
        rulesPayMethodFlag: '1',
        rulesOrderTypeFlag: '1',
        rulesVenueFlag: '1',
        rulesProjectFlag: '1',
        limitGetFlag: '1',
        rulesTimeSectionFlag: '1',

        couponsChannel: '1',
        couponsType: '0', // 优惠券类型 0-折扣券，1-代金券

        circulation: '', // 发行数量
        couponsId: '', // 优惠券id
        couponsName: '', // 优惠券名称
        couponsStatus: '', // 启用状态（0-禁用，1-启用）

        // discountNum: '', // 折扣/金额
        peoLimit: -1, // 每人限领数量
        receiveEndTime: '', // 领取结束时间
        receiveStartTime: '', // 领取开始时间
        useDes: '', // 使用说明
        useTimeInfo: '', // 适用时间文字描述
        validityDays: '', // 有效期天数
        validityStartTime: '', // 有效期开始时间
        validityEndTime: '', // 有效期到期时间
        validityType: '0', // 有效期类型0-固定期限，1-领取生效
        validityTime: [],
        timeLimit: [],
        useRules: {
          // 使用规则
          useStadiums: '', // 适用场馆
          useItems: '', // 适用项目
          orderTypes: '', // 订单类型
          payMethods: '', // 支付方式
          miniNum: null, // 最低消费
          useDateStart: '', // 适用开始日期
          useDateEnd: '', // 适用结束日期
          useDays: '', // 适用日，逗号分隔
          useTimeStart: '', // 适用开始时间
          useTimeEnd: '' // 适用结束时间
        }
      },
      rules
    }
  },
  created() {
    this.getVenueList()
    this.getVenueProjectList()
    this.getOrderTypeList()
    this.getPayTypeList()
  },
  methods: {
    closeDrawer() {
      this.isShowDrawer = false
      this.$emit('close')
    },
    formOnSubmit(formName) {
      const that = this
      this.$refs[formName].validate((valid) => {
        if (valid) {
          that.onSubmit()
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    changeType() {
      this.$set(this.param, 'discountNum', '')
    },
    changeLimit(val) {
      this.restrictType = ''
      if (val === '1') {
        this.param.peoLimit = -1
      } else {
        this.param.peoLimit = 1
      }
    },
    changeTimes() {
      this.$set(this.param, 'useTime', null)
      this.selWeekList = []
    },
    changePayMethods(val) {
      this.selPayTypeList = []
      this.param.useRules.payMethods = ''
    },
    changeOrderType() {
      this.selOrderTypeList = []
      this.param.useRules.orderTypes = null
    },
    changeVenue(val) {
      this.checkedVenue = []
      if (val === '0') {
        this.venueProjectListDataForTable = []
      } else {
        this.venueProjectListDataForTable = this.venueProjectListData
      }
      this.changeItems()
    },
    changeItems() {
      // this.checkVenue()
      this.checkedItems = []
      this.param.useRules.useItems = ''
    },
    // 获取场馆列表
    getVenueList() {
      venueList({
        param: {}
      })
        .then((res) => {
          if (res.errorCode !== '000000') return
          this.filters.venueList = res.recordList
        })
        .catch(() => {})
    },
    // 获取场馆项目
    getVenueProjectList() {
      venueProjectList({}).then((res) => {
        if (res.errorCode !== '000000') return
        this.venueProjectListData = res.recordList
        this.venueProjectListDataForTable = res.recordList || []
      })
    },
    // 获取订单类型列表
    getOrderTypeList() {
      orderTypeList({ param: { type: 'ORDER_TYPE_COUPONS' }}).then((res) => {
        if (res.errorCode !== '000000') return
        this.orderTypeList = res.recordList
      })
    },
    // 获取支付方式列表
    getPayTypeList() {
      allConfigList({ param: { type: '2', code: 'PAY_METHOD_COUPONS' }}).then((res) => {
        if (res.errorCode !== '000000') return
        this.payTypeList = res.recordList
      })
    },
    // 重置场馆项目选中状态
    resetVenueProject() {
      const { venueProjectListData, checkedVenue } = this
      const checedList = []
      if (checkedVenue.length === 0) {
        this.venueProjectListDataForTable = venueProjectListData
      } else {
        for (const i in venueProjectListData) {
          for (const j in checkedVenue) {
            if (venueProjectListData[i].id === checkedVenue[j]) {
              checedList.push(venueProjectListData[i])
            }
          }
        }
        this.venueProjectListDataForTable = checedList
      }
    },
    // 选择场馆
    checkVenue(e) {
      const { venueProjectListData } = this
      const { checkedItems } = this
      const checedList = []
      for (const i in venueProjectListData) {
        if (e.includes(venueProjectListData[i].id)) {
          checedList.push(venueProjectListData[i])
        }
      }

      this.venueProjectListDataForTable = checedList
      for (const i in venueProjectListData) {
        if (!e.includes(venueProjectListData[i].id)) {
          for (const project of venueProjectListData[i].projects) {
            if (this.checkedItems.includes(project.id)) {
              for (const key in this.checkedItems) {
                if (this.checkedItems[key] === project.id) {
                  checkedItems.splice(key, 1)
                }
              }
            }
          }
        }
      }
      this.checkedItems = checkedItems
    },
    // 选择项目
    checkProject(e) {
      console.log(e, this.checkedItems)
    },
    // 获取优惠券详情
    getCouponDetailInfo(couponsId) {
      couponsDetail({
        param: { couponsId },
        userId: sessionStorage.getItem('userId')
      })
        .then((res) => {
          if (res.errorCode !== '000000') return
          if (res.errorCode === '000000') {
            if (res.record.receiveEndTime) {
              const timeLimit = [res.record.receiveStartTime, res.record.receiveEndTime]
              res.record.timeLimit = timeLimit
            }
            this.param = res.record
            if (this.param.peoLimit == null) {
              this.param.peoLimit = -1
              this.$set(this.param, 'limitGetFlag', '1')
            } else {
              // this.param.peoLimit = -1
              this.$set(this.param, 'limitGetFlag', '0')
            }
            if (this.param.couponsType === '0') {
              this.param.discountNum = this.param.discountNum * 10
            }
            if (this.param.useRules.miniNum) {
              this.$set(this.param, 'miniNum', this.param.useRules.miniNum)
            }
            if (this.param.useRules.useDays) {
              this.selWeekList = this.param.useRules.useDays.includes(',')
                ? this.param.useRules.useDays.split(',')
                : [this.param.useRules.useDays]
            }
            if (this.param.useRules.payMethods) {
              this.selPayTypeList = this.param.useRules.payMethods.includes(',')
                ? this.param.useRules.payMethods.split(',')
                : [this.param.useRules.payMethods]
            }
            if (this.param.useRules.orderTypes) {
              this.selOrderTypeList = this.param.useRules.orderTypes.includes(
                ','
              )
                ? this.param.useRules.orderTypes.split(',')
                : [this.param.useRules.orderTypes]
            }
            if (this.param.useRules.useStadiums) {
              this.checkedVenue = this.param.useRules.useStadiums.includes(',')
                ? this.param.useRules.useStadiums.split(',')
                : [this.param.useRules.useStadiums]
            }
            if (this.param.useRules.useItems) {
              this.checkedItems = this.param.useRules.useItems.includes(',')
                ? this.param.useRules.useItems.split(',')
                : [this.param.useRules.useItems]
              this.$set(this.param, 'rulesProjectFlag', '0')
            } else {
              this.$set(this.param, 'rulesProjectFlag', '1')
            }
            if (res.record.validityStartTime && res.record.validityEndTime) {
              this.$set(this.param, 'validityTime', [res.record.validityStartTime, res.record.validityEndTime])
            } else {
              this.$set(this.param, 'validityTime', [])
            }
            if (res.record.useRules.useDateStart || res.record.useRules.useDateEnd) {
              this.$set(this.param, 'useDate', [res.record.useRules.useDateStart, res.record.useRules.useDateEnd])
            }
            if (res.record.useRules.useTimeStart || res.record.useRules.useTimeEnd) {
              this.$set(this.param, 'useTime', [res.record.useRules.useTimeStart, res.record.useRules.useTimeEnd])
            }
            this.resetVenueProject()
          }
        })
        .catch(() => {
          this.listLoading = false
        })
    },
    onSubmit() {
      const that = this
      // 代金券 金额校验
      if (this.param.couponsType === '1') {
        if (this.param.miniNum < this.param.discountNum) {
          return this.$message.warning('实付金额必须大于代金券金额')
        }
      } else {
        this.param.discountNum = this.param.discountNum / 10
      }
      if (this.param.validityType === '0') {
        this.param.validityStartTime = this.param.validityTime[0]
        this.param.validityEndTime = this.param.validityTime[1]
      } else {
        this.param.validityDays = parseInt(this.param.validityDays)
      }
      this.param.circulation = parseInt(this.param.circulation)
      if (this.param.timeLimit.length > 0) {
        const timeLimit = this.param.timeLimit
        this.param.receiveStartTime = timeLimit[0]
        this.param.receiveEndTime = timeLimit[1]
      }
      let param = JSON.stringify(this.param)
      param = JSON.parse(param)
      param.useRules.useStadiums = ''
      param.useRules.useItems = ''
      param.useRules.payMethods = ''
      param.useRules.orderTypes = ''
      if (this.checkedVenue.length) {
        param.useRules.useStadiums = this.checkedVenue.join(',')
      }
      if (this.checkedItems.length) {
        param.useRules.useItems = this.checkedItems.join(',')
      }
      if (this.selPayTypeList.length) {
        param.useRules.payMethods = this.selPayTypeList.join(',')
      }
      if (this.selOrderTypeList.length) {
        param.useRules.orderTypes = this.selOrderTypeList.join(',')
      }
      if (param.miniNum || param.miniNum === '0' || param.miniNum === 0) {
        param.useRules.miniNum = param.miniNum
      }
      // 适用日期校验
      param.useTimeInfo = ''
      param.useRules.useDays = ''
      if (param.useDate) {
        param.useRules.useDateStart = param.useDate[0]
        param.useRules.useDateEnd = param.useDate[1]
      }
      if (param.useDate) {
        param.useRules.useDateStart = param.useDate[0]
        param.useRules.useDateEnd = param.useDate[1]
      }
      if (this.selWeekList.length) {
        param.useRules.useDays = this.selWeekList.join(',')
      }
      // 适用时间校验
      if (param.useTime) {
        param.useRules.useTimeStart = param.useTime[0]
        param.useRules.useTimeEnd = param.useTime[1]
      }
      this.submitLoading = true
      if (this.id) {
        // 编辑
        couponsEdit({ param, userId: sessionStorage.getItem('userId') })
          .then((res) => {
            // console.log(res)
            that.submitLoading = false
            if (res.errorCode === '000000') {
              this.$message.success('编辑成功')
              this.isShowDrawer = false
              this.$emit('success')
            }
          })
          .catch((er) => {
            that.submitLoading = false
            console.log(er)
          })
      } else {
        couponsAdd({
          param: param,
          userId: sessionStorage.getItem('userId')
        })
          .then((res) => {
            that.submitLoading = false
            if (res.errorCode !== '000000') return
            this.$message.success('新增成功')
            this.isShowDrawer = false
            this.$emit('success')
          })
          .catch((err) => {
            that.submitLoading = false
            console.log(err)
          })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.separate{
  width: 100%;
  height: 1px;
  margin: 20px 0px;
  background-color: #DFE2E8;
}
.sub-title{
  font-size: 13px;
}
</style>
